package com.appspot.didit.client.user;

import com.appspot.didit.client.BaseView;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.inject.Inject;


public class LoginPresenterImpl implements LoginPresenter {
	private final UserServiceAsync userService = GWT.create(UserService.class);
	private final View view;
	
	@Inject
    public LoginPresenterImpl(final HandlerManager eventBus, final View view) {

            this.view = view;

            view.getLoginClickHandlers().addClickHandler(new ClickHandler() {
				@SuppressWarnings("unchecked")
				public void onClick(ClickEvent event) {
					login(eventBus);
				}
            });

            view.getLoginResetClickHandlers().addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					getView().reset();
					//eventBus.fireEvent(new LoginResetEvent());
					/*userService.generate(new AsyncCallback() {
	                    public void onFailure(Throwable caught) {
	                        GWT.log("Failed to get Result", caught);
	                    }
	                    public void onSuccess(Object result) {
	                    	 
	                    }		
	                });*/
				}
            });
            
            view.getKeyPressHandler().addKeyPressHandler(new KeyPressHandler() {
				@Override
				public void onKeyPress(KeyPressEvent event) {
					 if (event.getCharCode() == KeyCodes.KEY_ENTER) {
						 login(eventBus);
					 }
				}
            });

    }
            
    public void login(final HandlerManager eventBus) {
    	final String username = view.getUsername().getValue().toString();
		final String password = view.getPassword().getValue().toString();
		view.getWidget().getParent().getParent().setVisible(false);
		RootPanel.get("loading").setVisible(true);
		if(validate(username, password)) {
			userService.authenticate(username, password, new AsyncCallback() {
                public void onFailure(Throwable caught) {
                	RootPanel.get("loading").setVisible(false);
                	view.getWidget().getParent().getParent().setVisible(true);
                	view.getLoginHint().setText("Login failed!"); 
                    GWT.log("Login failed, Exception thrown", caught);
                }
                public void onSuccess(Object result) {
                    if (result != null) {
                    	User u = (User)result;
                    	UserManager um = UserManager.getInstance();
						um.setUser(u);
                    	eventBus.fireEvent(new LoginSuccessEvent());
                    } else {
                    	view.getWidget().getParent().getParent().setVisible(true);
                    	view.getLoginHint().setText("Login failed!"); 
                        GWT.log("Login failed", null);
                    }
                    RootPanel.get("loading").setVisible(false);
                }
            });
		} else {
			RootPanel.get("loading").setVisible(false);
			view.getLoginHint().setText("Sie haben Benutzename oder Passwort nicht eingegeben!");
			view.getWidget().getParent().getParent().setVisible(true);
		}
	}
    
    private boolean validate(String username, String password) {
    	System.out.println("validating...");
    	if(username == null || password == null) {
    		return false;
    	}
    	System.out.println("not null");
    	if(username.equals("") || password.equals("")) {
    		return false;
    	}
    	System.out.println("kein Leerzeichen");
    	return true;
    }

    	
    public View showLogin() {
            return view;
    }

    public BaseView getView() {
            return view;
    }
}
